var Admin = function() {
    return Admin.fn.init();
}




// Declare
Admin.fn = Admin.prototype = {

	init:function(){
		this.$el = $('#page-main-content');
	},

	$el:null,

	/**
	 * start js
	 */
	setup:function(mtype){
		switch(mtype) {
			case 'contacts_admin_index':
				var $add = this.$el.find('.add');
				this.addNewItem($add);
				this.removeItem($add.next());
				this.googleMap();

				this.editInfo(this.$el.find('.action .edit'));
				this.deleteInfo(this.$el.find('.action .delete'));
				break;

			case 'images_admin_index':
				this.deleteImage(this.$el.find('.tools a'));
				this.viewFullImage();

				this.changeCategory(this.$el.find('#ImageTargetId'));
				break;

			case 'images_admin_add':
				var $add = this.$el.find('.add');
				this.addNewItem($add);
				this.removeItem($add.next());
				break;

			case 'news_admin_index':
			case 'videos_admin_index':
				this.clearForm(this.$el.find('.form-actions .btn-warning'));
				this.actionIndex(this.$el.find('.adm-group-action'));
				this.confirmDeleteSubmit(this.$el.find('.adm-group-action button[type="submit"]'), 'Bạn có chắc chắc muốn đổi trạng thái những mẩu tin được chọn không ?');
				
				// Thay đổi danh mục
				this.changeCategory(this.$el.find('.change-category'));
				break;

			case 'abouts_admin_index':
			case 'abouts_admin_warranty':
			case 'abouts_admin_payment':
				this.initTinymce(400);
				break;

			case 'quotations_admin_index':
				this.initTinymce(150);
				break;

			case 'categories_admin_add':
			case 'news_admin_add':
				this.initTinymce();
				checkAlias();
				break;

			case 'codetbls_admin_index':
				// thay doi thu tu
				this.changeSort(this.$el.find('.change-sort'));

				this.clearForm(this.$el.find('.form-actions .btn-warning'));

				this.actionIndex(this.$el.find('.adm-group-action'));

				this.confirmDeleteSubmit(this.$el.find('.adm-group-action button[type="submit"]'), 'Bạn có chắc chắc muốn đổi trạng thái những mẩu tin được chọn không ?');
				break;
			
			case 'experts_admin_index':	
			case 'messages_admin_index':
				this.actionIndex(this.$el.find('.adm-group-action'));
				this.confirmDeleteSubmit(this.$el.find('.adm-group-action button[type="submit"]'), 'Bạn có chắc chắc muốn đổi trạng thái những mẩu tin được chọn không ?');
				break;

			case 'categories_admin_index':
				// thay doi thu tu
				this.changeSort(this.$el.find('.change-sort'));
				// Confrim xóa
				this.confirmDeleteSubmit( this.$el.find('.action-buttons .remove'), 'auto');
				break;

		}
	},

	/**
	 * Xóa dữ liệu form
	 */
	clearForm: function($html) {
		$html.click(function(event){
			event.preventDefault();
			clear_form_elements($(this).closest('form'));
		});
	},

	/**
	 * Change sort
	 */
	changeSort: function ($html) {
		var _this = this;
		$html.click(function(event){
			event.preventDefault();

			_this.$el.find('.alert').remove();

			var $obj = $(this);
			var data = $obj.data();

			var $input = $('<input type="text" style="width:32px; text-align: center;" value="'+ $obj.html()+'" />');
			$obj.after($input);
			$obj.hide();

			// Kiem tra validate sort
			_this.checkInputSort($input, $obj.html());

			$input.focus();

			$input.focusout(function(event){
				event.preventDefault();
				_this.$el.find('.alert').remove();
				var sort = $input.val();

				var json = {id:data.id, sort:sort};

				if(typeof(data.model) != 'undefined') json.model = data.model;

				postAjax(webroot + 'admin/'+ data.mode +'/changeSort', json, function(resp){
					var msg = 'Sửa thứ tự thất bại';
					if(resp.code == 'success'){
						$obj.html(sort);
						$obj.show();
						$input.remove();
						msg = 'Sửa thứ tự thành công';
					} else {
						$obj.show();
						$input.remove();
					}

					var $msg = $('<div class="alert alert-'+resp.code+'"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times"></i></button><p><strong>Thành Công:</strong><br> '+msg+'</p></div>');
					$obj.closest('table').before($msg);

					setTimeout(function(){
						$msg.slideUp(function(){ $(this).remove() });
					}, 3000);

				}, 'json', true);
			});
		});
	},

	/**
	 * Check validate sort
	 */
	checkInputSort: function($input, value) {
		$input.unbind().keyup(function(){
	        if (this.value.match(/[^0-9]/g)) {
		        this.value = value ? value : '';
	        }
	    });
	},

	/**
	 * Confirm Sumit
	 */
	confirmDeleteSubmit: function($html, msg) {
		var _this = this;
		$html.click(function(event){
			event.preventDefault();
			var $auto = msg == 'auto';
			var $btn = $(this);
			if($auto) {
				msg = $btn.data('confrim');
			}

			bootbox.confirm(msg, function(result) {
				if(result) {
					if($auto) {
						var $parent = $btn.parent();
						$parent.find('#CategoryId').val($btn.data('id')).attr('value', $btn.data('id'));
						$parent.find('#CategoryStatus').val($btn.data('status')).attr('value', $btn.data('status'));
					}
					$btn.closest('form').submit();
				}
			});
			return false;
		});
	},

	/**
	 * Thay đổi danh mục sản phẩm
	 */
	changeCategory: function ($html) {
		var _this = this;
		$html.change(function(event){
			var category_id = $(this).val();
			if (category_id.length <= 0 ) {
				category_id = _this.$el.find('#ProductParentId').val();
			}
			window.location.href = webroot + 'admin/' + $(this).data('mode') + '/index/' + category_id;
		});
	},

	/**
	 * Xóa hình ảnh
	 */
	deleteImage: function($html){
		var _this = this;
		$html.click(function(event){
			event.preventDefault();

			_this.$el.find('.alert').remove();

			var $item = $(this).closest('.item');

			//bootbox.setDefaults({locale: "vi"});
			bootbox.confirm("Bạn có chắc chắn muốn xóa hình ảnh này không?", function(result) {
				if(result) {
					postAjax(webroot + 'admin/products/deleteimg', {id:$item.attr('id')}, function(resp){

						var text = resp.code === 'success' ? 'Thành công' : 'Thất bại';
						var $msg = $('<div class="alert alert-'+resp.code+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button><p><strong>Thành công: </strong> '+resp.msg+'</p></div>');
						$item.parent().before($msg );

						setTimeout(function(){
							$msg.slideUp(function(){ $(this).remove() });
						}, 3000);

						if(resp.code === 'success'){
							$item.remove();
						}
					});
				}
			});
		});
	},

	/**
	 * Remove old image
	 */
	removeImage:function($html){
		$html.click(function(event){
			event.preventDefault();

			var $item = $(this).closest('.item');
			$imgdel = '<input type="hidden" name="data['+$item.data('als')+'][image_del][]" value="'+ $item.attr('id') +'"/>';
			$item.parent().before($imgdel);
			$item.remove();
		});
	},

	/**
	 * Them new item
	 */
	addNewItem:function($html) {
		var _this = this;
		$html.click(function(event){
			event.preventDefault();
			var $item = $(this).closest('.item');
			var $new = $item.clone();
			$item.find('.add').addClass('hide');
			$item.find('.del').removeClass('hide');
			$new.find('a').removeClass('hide');

			$new.find('.error-message').remove();

			$item.after($new);

			var data = $new.data();

			// Trường hợp ko có format name
			if(typeof(data.sort) == 'undefined') {
				$new.find('input').val('').attr('value', '');
			} else { // Trường hợp có format name
				var _sort = data.sort;
				$new.attr('data-sort', _sort + 1);

				$new.find('input').each(function( index ) {
					var $input = $(this);
					var name = $input.attr('name').replace(_sort, _sort + 1);

					$input.attr('name', name).removeClass('form-error');
					$input.val('').attr('value', '');
				});
			}

			_this.addNewItem($new.find('.add'));
			_this.removeItem($new.find('.del'));

		});
	},

	/**
	 * Xoa item upload image
	 */
	removeItem: function ($html) {
		$html.click(function(event){
			event.preventDefault();
			var $item = $(this).closest('.item');
			$items = $item.parent().find('.item');

			if($item.next().length == 0) {
				$item.prev().find('.add').removeClass('hide');
				if($items.length <= 2) {
					$item.prev().find('.del').addClass('hide');
				}
			} else {
				if($items.length <= 2) {
					$items.last().find('.del').addClass('hide');
				}

				$items.last().find('.add').removeClass('hide');
			}
			$item.remove();
		});
	},

	/**
	 * action admin_index adm-group-action
	 */
	actionIndex:function ($html) {
		var _this = this;

		$html.find('.dropdown-menu a').click(function(event){
			event.preventDefault();
			var $btn = $(this);
			$html.find('button.dropdown-toggle span').first().html($btn.html());
			$html.find('input[type="hidden"]').val($btn.data('status')).attr('value', $btn.data('status'));
		});
	},

	/**
	 * Delete Thông tin
	 */
	deleteInfo:function($html) {
		var _this = this;
		$html.click(function(event){
			event.preventDefault();
			_this.$el.find('.alert').remove();

			var $item = $(this).closest('._item');

			//bootbox.setDefaults({locale: "vi"});
			bootbox.confirm("Bạn có chắc chắn muốn xóa thông tin này không?", function(result) {
				if(result) {
					postAjax(webroot + 'admin/' + $item.data('mode') + '/delete', {id:$item.attr('id')}, function(resp){

						var text = resp.code === 'success' ? 'Thành công' : 'Thất bại';
						var $msg = $('<div class="alert mt10 alert-'+resp.code+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button><p><strong>Thông báo: </strong> '+resp.msg+'</p></div>');
						$item.closest('table').prev().before($msg );

						setTimeout(function(){
							$msg.slideUp(function(){ $(this).remove() });
						}, 3000);

						if(resp.code === 'success'){
							$item.slideUp(function(){ $(this).remove() });
						}
					});
				}
			});

		});
	},

	/**
	 * Sửa thông tin
	 */
	editInfo: function($html) {
		var _this = this;
		$html.unbind().click(function(event){
			event.preventDefault();
			var $btn = $(event.currentTarget);
			var $cancel = $btn.next();
			var $item = $btn.closest('._item');

			// Truong hop show input edit
			if( $btn.hasClass('edit') ) {
				$btn.removeClass('edit');

				$item.find('span').each(function( index ) {
					var span = $(this);
					var input = $('<input type="text" value="'+ span.html() +'" id="'+ span.data('field') +'" style="display:none" class="form-control '+ span.data('size') +'"/>');
					span.after(input);
					span.hide(300);
					input.show(300);
				});

				$btn.html('Lưu');
				$cancel.show(300);
				$cancel.unbind().click(function(event){
					event.preventDefault();
					_this.hideBtnEdit($(this), false);
				});
			} else { // Truong hop luu
				var json = {id:$item.attr('id')};
				$item.find('input').each(function( index ) {
					var $input = $(this);
					json[$input.attr('id')] = $input.val();
				});

				postAjax(webroot + 'admin/' + $item.data('mode') + '/' + $item.data('action'), json, function(resp){

					var text = resp.code === 'success' ? 'Thành công' : 'Thất bại';
					var $msg = $('<div class="alert mt10 alert-'+resp.code+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button><p><strong>Thông báo: </strong> '+resp.msg+'</p></div>');
					$item.closest('table').prev().before($msg );

					setTimeout(function(){
						$msg.slideUp(function(){ $(this).remove() });
					}, 3000);

					if(resp.code === 'success'){
						_this.hideBtnEdit($cancel, true);
					} else if(resp.errors){
						 $.each(resp.errors, function( idx, value ) {
	                        var $err = $('<div class="error-message">'+ value.msg +'</div>');
	                        $item.find('#' + value.id).addClass('form-error').after($err);
	                    });
					}
				});
			}
		});
	},

	/**
	 * Hide btn edit
	 */
	hideBtnEdit: function($btn, update) {
		var $item = $btn.closest('._item');
		var $input = $item.find('input');

		// Cap nhat lai thong tin
		if(update) {
			$input.each(function( index ) {
				$(this).prev().html($(this).val());
			});
		}

		$input.hide(300, function(){$(this).remove()});

		$item.find('.error-message').hide(300, function(){$(this).remove()});
		$item.find('span').show(300);

		$btn.prev().html('Sửa').addClass('edit');
		$btn.hide(300);
	},

	/**
	 * Google map
	 */
	googleMap:function() {
		var path = [ [lat,lng] ];

		map = new GMaps({
	        el: '#map',
	        zoom: 16,
	        lat: lat,
	        lng: lng
		});

		polygon = map.drawPolygon({
	        paths: path,
	        strokeColor: '#BBD8E9',
	        strokeOpacity: 1,
	        strokeWeight: 3,
	        fillColor: '#BBD8E9',
	        fillOpacity: 0.6
		});

		map.addMarker({
	        lat: lat,
	        lng: lng,
	        infoWindow: {
		        content: '<p>'+ address +'</p>'
		    },
	        title: address,
			draggable: true,
			fences: [polygon],
			outside: function(m, f){
				postAjax( webroot + 'admin/contacts/location', {lat: m.position.k, lng: m.position.B}, function(resp){});
	        }
		});

		// show infoWindow
		map.markers[0].infoWindow.open(map, map.markers[0]);
	},

	/**
	 * Xem full hinh ảnh
	 */
	viewFullImage: function() {
		var _this = this;
		var $overflow = '';
		var colorbox_params = {
			rel: 'colorbox',
			//slideshow:true,
			reposition:true,
			scalePhotos:true,
			scrolling:false,
			previous:'<i class="fa fa-arrow-left text-gray"></i>',
			next:'<i class="fa fa-arrow-right text-gray"></i>',
			close:'<i class="fa fa-times text-gray"></i>',
			current:'{current} of {total}',
			//slideshowStart: "Chạy",
//			slideshowStop: "Ngừng",
//			slideshow:true,
			maxWidth:'100%',
			maxHeight:'100%',
			onOpen:function(){
				$overflow = document.body.style.overflow;
				document.body.style.overflow = 'hidden';
			},
			onClosed:function(){
				document.body.style.overflow = $overflow;
			},
			onComplete:function(){
				$.colorbox.resize();
			}
		};

		this.$el.find('.tc-gallery [data-rel="colorbox"]').colorbox(colorbox_params);
		this.$el.find("#cboxLoadingGraphic").append("<i class='fa fa-spinner fa-spin'></i>");//let's add a custom loading icon
	},

	/**
	 * tinymce
	 */
	initTinymce: function(height) {
		var size = new Array();

		for(i=8; i <= 36; i++ ) {
			size[i-8] = { title: i + 'px', inline: 'span', styles: { 'font-size': i + 'px'} } ;
		}

		if(!height) height = 300;
		tinymce.init({
		   	height:height,
			document_base_url: full_base_url,
			relative_urls : false,
			remove_script_host : true,
		    selector: "textarea.tnmc",
		    theme: "modern",
		    //skin:'custom',
		    language:'vi_VN',
		    style_formats: size,
		    font_formats:   "Andale Mono=andale mono,times;"+
					        "Arial=arial,helvetica,sans-serif;"+
					        "Arial Black=arial black,avant garde;"+
					        "Book Antiqua=book antiqua,palatino;"+
					        "Comic Sans MS=comic sans ms,sans-serif;"+
					        "Courier New=courier new,courier;"+
					        "Georgia=georgia,palatino;"+
					        "Helvetica=helvetica;"+
					        "Impact=impact,chicago;"+
					        "Symbol=symbol;"+
					        "Tahoma=tahoma,arial,helvetica,sans-serif;"+
					        "Terminal=terminal,monaco;"+
					        "Times New Roman=times new roman,times;"+
					        "Trebuchet MS=trebuchet ms,geneva;"+
					        "Verdana=verdana,geneva;"+
					        "Webdings=webdings;"+
					        "Wingdings=wingdings,zapf dingbats",
		    subfolder:"",
		    plugins: [
		         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
		         "searchreplace wordcount visualblocks visualchars code insertdatetime media nonbreaking",
		         "table contextmenu directionality emoticons paste textcolor  filemanager"
		   ],
		   image_advtab: true,
		   toolbar_items_size: 'small',
		   toolbar: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect fontselect | forecolor backcolor emoticons | link unlink anchor image | preview code"
		});
	}


}

var admin = new Admin();
